<template>
  <main-tpl>
    <template #main>
      <div class="video-detail">
        <div class="video-detail-button">
          <a-button @click="back">返回</a-button>
        </div>
        <div class="video-detail-main">
          <div class="video-detail-player">
            <vue3-video-play v-bind="options" />
            <div class="video-detail-player-desc">
              <div class="video-detail-player-desc-title">
                <span>视频标识名称：{{ detail?.name || "" }}</span>
                <span>视频分组：{{ getGroupName(detail?.groupId) }}</span>
              </div>
              <div class="video-detail-player-desc-log">
                任务日志：
                <div class="video-detail-player-desc-log-value">{{ detail?.log || "" }}</div>
              </div>
            </div>
          </div>
          <div class="video-detail-content">
            <div class="video-detail-content-title">识别结果</div>
            <a-tabs v-model:activeKey="activeKey">
              <a-tab-pane
                v-for="(result, index) in detail?.results || []"
                :key="index"
                :tab="getPlayerName(result.playerId)"
              >
                <div class="video-detail-content-tab">
                  <span>分组：{{ getGroupName(result.groupId) }}</span>
                  <div class="video-detail-content-tab-button">
                    <a-button type="primary" :loading="downloadLoading" @click="download(result)"
                      >下载</a-button
                    >
                    <a-button
                      style="margin-left: 8px"
                      :loading="produceLoading"
                      @click="produce(result)"
                      >生成</a-button
                    >
                  </div>
                </div>
                <a-table
                  v-if="dataSource"
                  size="middle"
                  :scroll="{ x: '100%', y: 550 }"
                  :columns="columns"
                  :pagination="false"
                  :data-source="dataSource"
                ></a-table>
              </a-tab-pane>
            </a-tabs>
          </div>
        </div>
      </div>
    </template>
  </main-tpl>
</template>
<script>
import { onMounted, reactive, toRefs, nextTick, computed } from "vue";
import { useRouter } from "vue-router";
import { downloadFile } from "@/api/common";
import { detailVideoTask, getGroupList, getPlayerList, clipsVideoTask } from "@/api/marathon";
import { message } from "ant-design-vue";

const columns = [
  {
    title: "id",
    dataIndex: "id",
    key: "id",
    width: 50,
  },
  {
    title: "开始时间",
    dataIndex: "startTime",
    key: "startTime",
  },
  {
    title: "结束时间",
    dataIndex: "endTime",
    key: "endTime",
  },
];

export default {
  name: "VideoDetail",

  setup() {
    const options = reactive({
      width: "800px", //播放器高度
      height: "450px", //播放器高度
      color: "#409eff", //主题色
      title: "", //视频名称
      src: "", //视频源
      muted: false, //静音
      webFullScreen: false,
      speedRate: ["0.75", "1.0", "1.25", "1.5", "2.0"], //播放倍速
      autoPlay: false, //自动播放
      loop: false, //循环播放
      mirror: false, //镜像画面
      lightOff: false, //关灯模式
      volume: 0.3, //默认音量大小
      control: true, //是否显示控制器
    });

    const router = useRouter();
    const back = () => {
      router.go(-1);
    };

    const state = reactive({
      modalVisible: false,
      detail: {},
      activeKey: 0,
      groupOptions: [],
      playerOptions: [],
      downloadLoading: false,
      produceLoading: false,
    });

    const init = () => {
      if (router.currentRoute.value.query.id) {
        getDetail(router.currentRoute.value.query.id);
      }
    };

    onMounted(() => {
      nextTick(() => {
        init();
        initGroups();
        initPlayers();
      });
    });

    const initGroups = () => {
      const dto = {
        pageNumber: 1,
        pageSize: 1000,
      };
      getGroupList(dto).then((res) => {
        if (res.result === true) {
          let { responseList = [] } = res?.data;
          state.groupOptions = responseList;
        } else {
          message.error("获取分组列表失败：" + res.message);
        }
        state.loading = false;
      });
    };

    const getGroupName = (groupId) => {
      return state.groupOptions?.find((item) => item.id === groupId)?.name || "-";
    };

    const initPlayers = () => {
      const dto = {
        pageNumber: 1,
        pageSize: 1000,
      };
      getPlayerList(dto).then((res) => {
        if (res.result === true) {
          let { responseList = [] } = res?.data;
          state.playerOptions = responseList;
        } else {
          message.error("获取分组列表失败：" + res.message);
        }
        state.loading = false;
      });
    };

    const getPlayerName = (groupId) => {
      return state.playerOptions?.find((item) => item.id === groupId)?.name || "-";
    };

    const getDetail = (id) => {
      const dto = {
        id: id,
      };
      detailVideoTask(dto).then((res) => {
        if (res.result === true) {
          state.detail = res.data;
          options.src = downloadFile(state.detail.filepath);
        } else {
          message.error("获取视频详情失败：" + res.message);
        }
      });
    };

    const getResultTableData = (data) => {
      if (data) {
        const res = JSON.parse(data);
        return Array.isArray(res) ? res : [];
      }
      return [];
    };

    const dataSource = computed(() => {
      return getResultTableData(state.detail?.results[state.activeKey]?.result);
    });

    const download = (result) => {
      if (result?.filepath) {
        downloadMethod(result.filepath);
      } else {
        message.error("无下载内容");
      }
    };

    const downloadMethod = (path) => {
      const url = downloadFile(path);
      const lastIndex = path.lastIndexOf("/") + 1;
      const fileName = path.substring(lastIndex);
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = () => {
        const u = window.URL.createObjectURL(xhr.response);
        let a = document.createElement("a");
        a.href = u;
        a.download = fileName;
        a.click();
        a.remove();
      };
      xhr.send();
    };

    const produce = (result) => {
      state.produceLoading = true;
      const dto = {
        resultId: result.id,
        filepath: state.detail.filepath,
        clipPoints: getResultTableData(result.result),
      };
      clipsVideoTask(dto).then((res) => {
        if (res.result && res.data) {
          message.success("生成成功，请查看浏览器下载");
          downloadMethod(res.data);
        } else {
          message.error("生成失败");
        }
        state.produceLoading = false;
      });
    };

    return {
      ...toRefs(state),
      options,
      back,
      getGroupName,
      getPlayerName,
      columns,
      download,
      produce,
      dataSource,
    };
  },
};
</script>
<style lang="scss" scoped>
.video-detail {
  height: 100%;
  .video-detail-main {
    display: flex;
    flex-direction: row;
    margin-top: 16px;
    .video-detail-player-desc {
      margin-top: 16px;
      .video-detail-player-desc-title {
        font-size: 16px;
        span + span {
          padding-left: 120px;
        }
      }
      .video-detail-player-desc-log {
        margin-top: 8px;
        .video-detail-player-desc-log-value {
          white-space: pre-line;
          margin-top: 8px;
          padding: 10px;
          border: 1px solid #ccc;
          width: 100%;
          height: 200px;
          overflow: auto;
        }
      }
    }

    .video-detail-content {
      width: 100%;
      height: 100%;
      margin-left: 40px;
      .video-detail-content-title {
        font-size: 24px;
        font-weight: bold;
      }
      .video-detail-content-tab {
        padding-bottom: 8px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
}
</style>
